package com.basin.micro.auth.module.account.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.basin.common.core.exception.BasinException;
import com.basin.micro.auth.component.RsaCoder;
import com.basin.micro.auth.module.account.pojo.entity.EmpAccountEntity;
import com.basin.micro.auth.module.account.repository.EmpAccountRepository;
import com.basin.micro.auth.module.account.service.AccountService;
import com.basin.micro.auth.module.sign.strategy.login.web.form.UPForm;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
@Service
@Slf4j(topic = "BASIN:AUTH:ACCOUNT_SERVICE")
@RequiredArgsConstructor
public class AccountServiceImpl implements AccountService {
    private final EmpAccountRepository empAccountRepository;
    private final RsaCoder rsaCoder;

    @Value("${auth_account.emp_init_password:123456}")
    private String initPassword;

    @Override
    public void initEmpAccountAuth(String empId) {
        if (ObjectUtil.isEmpty(empId)) throw new BasinException("员工ID不能为空");
        long count = empAccountRepository.count(Wrappers.<EmpAccountEntity>lambdaQuery()
                .eq(EmpAccountEntity::getAccount, empId));
        if (count != 0) throw new BasinException("员工账号已存在");
        // 初始化密码
        String pwd = this.rsaCoder.encode(initPassword);
        String decodePwd = this.rsaCoder.decode(pwd);
        EmpAccountEntity empAccountEntity = EmpAccountEntity.builder()
                .account(empId)
                .password(pwd)
                .build();
        boolean save = empAccountRepository.save(empAccountEntity);
        if (!save) throw new BasinException("员工账号信息保存失败");
    }

    @Override
    public String empAccountLoginViaUP(UPForm upForm) {
        var account = upForm.getUsername();
        if (ObjectUtil.isEmpty(account)) throw new BasinException("账号必填");
        String password = upForm.getPassword();
        if (ObjectUtil.isEmpty(password)) throw new BasinException("密码必填");
        // 查找用户
        EmpAccountEntity empAccountInfo = this.empAccountRepository.getOne(Wrappers.<EmpAccountEntity>lambdaQuery()
                .eq(EmpAccountEntity::getAccount, account));
        if (ObjectUtil.isEmpty(empAccountInfo)) throw new BasinException("账号不存在");
        boolean equal = rsaCoder.isEqual(password, empAccountInfo.getPassword());
        if (!equal) throw new BasinException("账号或密码错误");
        StpUtil.login(empAccountInfo.getAccount()); // login
        return StpUtil.getTokenValue(); // 获取token
    }
}
